<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="./css/bootstrap.min.css">
    <script src="./js/jquery-3.1.1.min.js"></script>
    <script src="./js/bootstrap.min.js"></script>
    <script src="./js/echarts.min.js"></script>
    <script src="./js/layer_v3.1.1/3.1.1/layer.js"></script>
    <style>
        .upload-btn {
            position: relative;
        }

        .upload-btn input {
            opacity: 0;
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            z-index: 1;
            cursor: pointer;
        }

        .custom-select-attack {
            pointer-events: none;
        }

        .container {
            position: absolute;
            left: 50%;
            top: 30%;
            transform: translate(-50%, -50%);
        }

        .card-img-top {
            width: 280px;
            height: 280px;
            object-fit: cover;
        }

        .chart {
            width: 100%;
            height: 200px;
        }

        .carousel-item {
            min-height: 200px;
            background: #000;
            pointer-events: none;
            color: #fff;
            padding: 20px 42px;
            box-sizing: border-box;
        }

        .carousel-control-prev, .carousel-control-next {
            background: none;
            border: none;
        }

        .modal {
            overflow: auto;
        }

        .image-box-wrapper {
            gap: 10px;
        }

        .image-box {
            flex: 1;
            box-sizing: border-box;
            padding: 10px;
            border-radius: 5px;
            border: 3px dashed;
            aspect-ratio: 1/0.7;
            position: relative;
        }

        .image-box:nth-child(1) {
            border-color: #34ce57;
        }

        .image-box:nth-child(2) {
            border-color: #ccc;
        }

        .image-box:nth-child(1):hover {
            border-color: #1c7430;
        }

        .image-box:nth-child(2):hover {
            border-color: #000;
        }

        .image-box .input-file {
            opacity: 0;
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            z-index: 1;
            cursor: pointer;
        }

        .image-box img {
            width: 100%;
            height: 100%;
            object-fit: contain;
            display: none;
        }
    </style>
</head>
<body>

<div class="container mt-4 mb-3">
    <h2 class="title">对抗攻防系统</h2>
    <div class="mt-3 d-flex align-content-center justify-content-between">
        <form action="" class="form-inline" id="attack-form">
            <input type="hidden" name="originImg" id="origin-img">
            <div class="form-group">
                <button type="button" class="btn btn-primary btn-sm d-flex align-items-center upload-btn">
                    <svg t="1724739782789" class="icon" viewBox="0 0 1024 1024" version="1.1"
                         xmlns="http://www.w3.org/2000/svg" p-id="1630" width="20" height="20">
                        <path d="M474 152m8 0l60 0q8 0 8 8l0 704q0 8-8 8l-60 0q-8 0-8-8l0-704q0-8 8-8Z"
                              fill="#ffffff" p-id="1631"></path>
                        <path d="M168 474m8 0l672 0q8 0 8 8l0 60q0 8-8 8l-672 0q-8 0-8-8l0-60q0-8 8-8Z"
                              fill="#ffffff" p-id="1632"></path>
                    </svg>
                    <span>添加图片</span>
                    <input type="file" accept="image/*"
                           onchange="chooseFile(this, 'origin-img', document.querySelector('.image-box:nth-child(1)>img'))">
                </button>
            </div>
            <div class="form-group ml-2">
                <label>攻击模型</label>
                <select class="form-control form-control-sm ml-2" name="attackModel" required>
                    <option value="t2t-vit" selected>t2t-vit</option>
                    <option value="faster-vit">faster-vit</option>
                    <option value="alexnet">alexnet</option>
                    <option value="efficientnet_l">efficientnet_l</option>
                </select>
            </div>
            <div class="form-group ml-2" data-toggle="modal" data-target="#attackFormModal">
                <label>攻击算法</label>
                <select class="form-control form-control-sm ml-2 custom-select-attack" name="attackAlgorithm"
                        required>
                    <option value="ta" selected>ta</option>
                    <option value="bda">boundary attack</option>
                    <option value="nes">nes</option>
                    <option value="opt">sign-opt</option>
                    <option value="deep-fool">deep fool</option>
                    <option value="mim">mim</option>
                    <option value="cw-white">cw white</option>
                    <option value="pgd">pgd</option>
                </select>
            </div>
            <div class="form-group ml-2">
                <label>防御算法</label>
                <select class="form-control form-control-sm ml-2" name="defenseAlgorithm" required>
                    <option value="PRN" selected>PRN</option>
                    <option value="ffdn">FFDNet</option>
                    <option value="rd">随机平滑</option>
                    <option value="lgs">局部梯度平滑</option>
                </select>
            </div>
            <div class="form-group ml-2">
                <label>设备</label>
                <select class="form-control form-control-sm ml-2" name="device" required>
                    <option value="cpu" selected>CPU</option>
                    <option value="cuda">GPU</option>
                </select>
            </div>
        </form>
        <div class="text-right">
            <button class="btn btn-primary btn-sm" onclick="attack()">开始模拟</button>
            <button type="button" class="btn btn-primary btn-sm upload-btn">
                <span>自适应评估</span>
                <input type="file" multiple directory webkitdirectory mozdirectory onchange="chooseDirectory(this)">
            </button>
        </div>
    </div>
    <div class="d-flex align-content-center justify-content-between mt-3 image-box-wrapper">
        <div class="image-box">
            <input type="file" class="input-file" accept="image/*"
                   onchange="chooseFile(this, 'origin-img', document.querySelector('.image-box:nth-child(1)>img'))">
            <img src="" alt="">
        </div>
        <div class="image-box">
            <input type="file" class="input-file" accept="image/*"
                   onchange="chooseFile(this, 'target-image', document.querySelector('.image-box:nth-child(2)>img'))">
            <img src="" alt="">
        </div>
    </div>
</div>

<!-- 攻击算法选择Modal -->
<div class="modal fade" id="attackFormModal" tabindex="-1" role="dialog" aria-labelledby="attackFormModalLabel"
     aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="attackFormModalLabel">攻击算法</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <nav class="nav nav-pills flex-column flex-sm-row attack-type-tabs">
                    <a class="flex-sm-fill text-sm-center nav-link active" data-target="black-box" href="#">黑盒</a>
                    <a class="flex-sm-fill text-sm-center nav-link" data-target="white-box" href="#">白盒</a>
                </nav>
                <div id="black-box" class="attack-type mt-2">
                    <nav class="nav nav-pills flex-column flex-sm-row attack-algorithm-tabs">
                        <a class="flex-sm-fill text-sm-center nav-link active" data-target="ta" href="#">ta</a>
                        <a class="flex-sm-fill text-sm-center nav-link" data-target="bda" href="#">bda</a>
                        <a class="flex-sm-fill text-sm-center nav-link" data-target="nes" href="#">nes</a>
                        <a class="flex-sm-fill text-sm-center nav-link" data-target="opt" href="#">opt</a>
                    </nav>
                    <form id="ta-form" class="attack-algorithm-form mt-3">
                        <div class="form-group">
                            <label>Max Queries</label>
                            <input type="number" step="any" name="max_queries" class="form-control" placeholder="1000">
                        </div>
                        <div class="form-group">
                            <label>Ratio Mask</label>
                            <input type="number" step="any" name="ratio_mask" class="form-control"
                                   placeholder="0.1">
                        </div>
                        <div class="form-group">
                            <label>Dim Num</label>
                            <input type="number" step="any" name="dim_num"
                                   class="form-control" placeholder="1">
                        </div>
                        <div class="form-group">
                            <label>Max Iter Num In 2d</label>
                            <input type="number" step="any" name="max_iter_num_in_2d"
                                   class="form-control" placeholder="2">
                        </div>
                        <div class="form-group">
                            <label>Init Theta</label>
                            <input type="number" step="any" name="init_theta"
                                   class="form-control" placeholder="2">
                        </div>
                        <div class="form-group">
                            <label>Init Alpha</label>
                            <input type="number" step="any" name="init_alpha"
                                   class="form-control" placeholder="pi / 2">
                        </div>
                        <div class="form-group">
                            <label>Plus Learning Rate</label>
                            <input type="number" step="any" name="plus_learning_rate" class="form-control"
                                   placeholder="0.1">
                        </div>
                        <div class="form-group">
                            <label>Minus Learning Rate</label>
                            <input type="number" step="any" name="minus_learning_rate" class="form-control"
                                   placeholder="0.005">
                        </div>
                        <div class="form-group">
                            <label>Half Range</label>
                            <input type="number" step="any" name="half_range" class="form-control"
                                   placeholder="0.1">
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                            <button class="btn btn-primary">保存</button>
                        </div>
                    </form>
                    <form id="bda-form" style="display: none" class="attack-algorithm-form mt-3">
                        <div class="form-group">
                            <label>Target Image</label>
                            <div class="custom-file">
                                <input type="file"
                                       onchange="chooseFile(this, 'target-image', document.querySelector('.image-box:nth-child(2)>img'))"
                                       accept="image/*"
                                       class="custom-file-input" id="customFile">
                                <label class="custom-file-label" for="customFile">Choose file</label>
                            </div>
                            <input type="text" readonly class="form-control" required name="targetImage"
                                   id="target-image">
                        </div>
                        <div class="form-group">
                            <label>Epsilon</label>
                            <input type="number" step="any" name="epsilon" class="form-control" placeholder="1.0">
                        </div>
                        <div class="form-group">
                            <label>Delta</label>
                            <input type="number" step="any" name="delta" class="form-control" placeholder="0.1">
                        </div>
                        <div class="form-group">
                            <label>Max Step</label>
                            <input type="number" step="any" name="maxStep" class="form-control" placeholder="100">
                        </div>
                        <div class="form-group">
                            <label>Min Diff</label>
                            <input type="number" step="any" name="minDiff" class="form-control" placeholder="1e-3">
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                            <button class="btn btn-primary">保存</button>
                        </div>
                    </form>
                    <form id="nes-form" style="display: none" class="attack-algorithm-form mt-3">
                        <div class="form-group">
                            <label>Targeted</label>
                            <select name="targeted" class="form-control" required>
                                <option value="1">True</option>
                                <option value="0" selected>False</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Epsilon</label>
                            <input type="number" step="any" name="epsilon" class="form-control" placeholder="0.05">
                        </div>
                        <div class="form-group">
                            <label>Step</label>
                            <input type="number" step="any" name="step" class="form-control" placeholder="100">
                        </div>
                        <div class="form-group">
                            <label>Lr</label>
                            <input type="number" step="any" name="lr" class="form-control" placeholder="0.01">
                        </div>
                        <div class="form-group">
                            <label>N</label>
                            <input type="number" step="any" name="n" class="form-control" placeholder="10">
                        </div>
                        <div class="form-group">
                            <label>Sigma</label>
                            <input type="number" step="any" name="sigma" class="form-control" placeholder="1e-3">
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                            <button class="btn btn-primary">保存</button>
                        </div>
                    </form>
                    <form id="opt-form" style="display: none" class="attack-algorithm-form mt-3">
                        <div class="form-group">
                            <label>Distortion</label>
                            <select name="distortion" class="form-control" required>
                                <option value="1">True</option>
                                <option value="0" selected>False</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Svm</label>
                            <select name="svm" class="form-control" required>
                                <option value="1">True</option>
                                <option value="0" selected>False</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Max Query</label>
                            <input type="number" step="any" name="maxQuery" class="form-control" placeholder="4000">
                        </div>
                        <div class="form-group">
                            <label>Momentum</label>
                            <input type="number" step="any" name="momentum" class="form-control" placeholder="0">
                        </div>
                        <div class="form-group">
                            <label>Alpha</label>
                            <input type="number" step="any" name="alpha" class="form-control" placeholder="0.2">
                        </div>
                        <div class="form-group">
                            <label>Beta</label>
                            <input type="number" step="any" name="beta" class="form-control" placeholder="0.001">
                        </div>
                        <div class="form-group">
                            <label>Iterations</label>
                            <input type="number" step="any" name="iterations" class="form-control" placeholder="1">
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                            <button class="btn btn-primary">保存</button>
                        </div>
                    </form>
                </div>
                <div id="white-box" class="attack-type mt-2" style="display: none">
                    <nav class="nav nav-pills flex-column flex-sm-row attack-algorithm-tabs">
                        <a class="flex-sm-fill text-sm-center nav-link active" data-target="deep-fool" href="#">deep
                            fool</a>
                        <a class="flex-sm-fill text-sm-center nav-link" data-target="mim" href="#">mim</a>
                        <a class="flex-sm-fill text-sm-center nav-link" data-target="cw-white" href="#">cw</a>
                        <a class="flex-sm-fill text-sm-center nav-link" data-target="pgd" href="#">pgd</a>
                    </nav>
                    <form id="deep-fool-form" style="display: none" class="attack-algorithm-form mt-3">
                        <div class="form-group">
                            <label>Step</label>
                            <input type="number" step="any" name="step" class="form-control" placeholder="50">
                        </div>
                        <div class="form-group">
                            <label>Overshot</label>
                            <input type="number" step="any" name="overshot" class="form-control" placeholder="0.02">
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                            <button class="btn btn-primary">保存</button>
                        </div>
                    </form>
                    <form id="mim-form" style="display: none" class="attack-algorithm-form mt-3">
                        <div class="form-group">
                            <label>Epsilon</label>
                            <input type="number" step="any" name="epsilon" class="form-control" placeholder="8 / 255">
                        </div>
                        <div class="form-group">
                            <label>Step</label>
                            <input type="number" step="any" name="step" class="form-control" placeholder="10">
                        </div>
                        <div class="form-group">
                            <label>Decay</label>
                            <input type="number" step="any" name="decay" class="form-control" placeholder="1.0">
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                            <button class="btn btn-primary">保存</button>
                        </div>
                    </form>
                    <form id="cw-white-form" style="display: none" class="attack-algorithm-form mt-3">
                        <div class="form-group">
                            <label>C</label>
                            <input type="number" step="any" name="c" class="form-control" placeholder="1">
                        </div>
                        <div class="form-group">
                            <label>Kappa</label>
                            <input type="number" step="any" name="kappa" class="form-control" placeholder="0">
                        </div>
                        <div class="form-group">
                            <label>Steps</label>
                            <input type="number" step="any" name="steps" class="form-control" placeholder="50">
                        </div>
                        <div class="form-group">
                            <label>Lr</label>
                            <input type="number" step="any" name="lr" class="form-control" placeholder="0.01">
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                            <button class="btn btn-primary">保存</button>
                        </div>
                    </form>
                    <form id="pgd-form" style="display: none" class="attack-algorithm-form mt-3">
                        <div class="form-group">
                            <label>Epsilon</label>
                            <input type="number" step="any" name="epsilon" class="form-control" placeholder="8 / 255">
                        </div>
                        <div class="form-group">
                            <label>Alpha</label>
                            <input type="number" step="any" name="alpha" class="form-control" placeholder="2 / 255">
                        </div>
                        <div class="form-group">
                            <label>Steps</label>
                            <input type="number" step="any" name="steps" class="form-control" placeholder="10">
                        </div>
                        <div class="form-group">
                            <label>Random Started</label>
                            <select name="randomStarted" class="form-control" required>
                                <option value="1" selected>True</option>
                                <option value="0">False</option>
                            </select>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                            <button class="btn btn-primary">保存</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 攻击结果展示Modal -->
<div class="modal fade" id="attackResultModal" tabindex="-1" role="dialog" aria-labelledby="attackResultModalLabel"
     aria-hidden="true">
    <div class="modal-dialog" style="max-width: 950px;" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="attackResultModalLabel">攻击结果</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="row">

                </div>
            </div>
        </div>
    </div>
</div>

<!--自适应评估表单-->
<div class="modal fade" id="aotuEvaFormModal" tabindex="-1" role="dialog" aria-labelledby="aotuEvaFormModalLabel"
     aria-hidden="true">
    <div class="modal-dialog" style="max-width: 950px;" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="aotuEvaFormModalLabel">自适应评估</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form action="" class="aotu-eva-form">
                    <div class="row">
                        <div class="col-4">
                            <div class="card">
                                <div class="card-header">
                                    <div class="card-title">ta</div>
                                </div>
                                <div class="card-body">
                                    <div id="aotu-eva-ta-form" class="aotu-eva-form-wrapper" data-form-name="attach_ta">
                                        <div class="form-group">
                                            <label>Max Queries</label>
                                            <input type="number" step="any" name="max_queries" class="form-control"
                                                   placeholder="1000">
                                        </div>
                                        <div class="form-group">
                                            <label>Ratio Mask</label>
                                            <input type="number" step="any" name="ratio_mask" class="form-control"
                                                   placeholder="0.1">
                                        </div>
                                        <div class="form-group">
                                            <label>Dim Num</label>
                                            <input type="number" step="any" name="dim_num"
                                                   class="form-control" placeholder="1">
                                        </div>
                                        <div class="form-group">
                                            <label>Max Iter Num In 2d</label>
                                            <input type="number" step="any" name="max_iter_num_in_2d"
                                                   class="form-control" placeholder="2">
                                        </div>
                                        <div class="form-group">
                                            <label>Init Theta</label>
                                            <input type="number" step="any" name="init_theta"
                                                   class="form-control" placeholder="2">
                                        </div>
                                        <div class="form-group">
                                            <label>Init Alpha</label>
                                            <input type="number" step="any" name="init_alpha"
                                                   class="form-control" placeholder="pi / 2">
                                        </div>
                                        <div class="form-group">
                                            <label>Plus Learning Rate</label>
                                            <input type="number" step="any" name="plus_learning_rate"
                                                   class="form-control"
                                                   placeholder="0.1">
                                        </div>
                                        <div class="form-group">
                                            <label>Minus Learning Rate</label>
                                            <input type="number" step="any" name="minus_learning_rate"
                                                   class="form-control"
                                                   placeholder="0.005">
                                        </div>
                                        <div class="form-group">
                                            <label>Half Range</label>
                                            <input type="number" step="any" name="half_range" class="form-control"
                                                   placeholder="0.1">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-4">
                            <div class="card">
                                <div class="card-header">
                                    <div class="card-title">nes</div>
                                </div>
                                <div class="card-body">
                                    <div id="aotueva-nes-form" class="aotu-eva-form-wrapper"
                                         data-form-name="attach_bda">
                                        <div class="form-group">
                                            <label>Targeted</label>
                                            <select name="targeted" class="form-control" required>
                                                <option value="1">True</option>
                                                <option value="0" selected>False</option>
                                            </select>
                                        </div>
                                        <div class="form-group">
                                            <label>Epsilon</label>
                                            <input type="number" step="any" name="epsilon" class="form-control"
                                                   placeholder="0.05">
                                        </div>
                                        <div class="form-group">
                                            <label>Step</label>
                                            <input type="number" step="any" name="step" class="form-control"
                                                   placeholder="100">
                                        </div>
                                        <div class="form-group">
                                            <label>Lr</label>
                                            <input type="number" step="any" name="lr" class="form-control"
                                                   placeholder="0.01">
                                        </div>
                                        <div class="form-group">
                                            <label>N</label>
                                            <input type="number" step="any" name="n" class="form-control"
                                                   placeholder="10">
                                        </div>
                                        <div class="form-group">
                                            <label>Sigma</label>
                                            <input type="number" step="any" name="sigma" class="form-control"
                                                   placeholder="1e-3">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-4">
                            <div class="card">
                                <div class="card-header">
                                    <div class="card-title">opt</div>
                                </div>
                                <div class="card-body">
                                    <div id="aotueva-opt-form" class="aotu-eva-form-wrapper"
                                         data-form-name="attach_opt">
                                        <div class="form-group">
                                            <label>Distortion</label>
                                            <select name="distortion" class="form-control" required>
                                                <option value="1">True</option>
                                                <option value="0" selected>False</option>
                                            </select>
                                        </div>
                                        <div class="form-group">
                                            <label>Svm</label>
                                            <select name="svm" class="form-control" required>
                                                <option value="1">True</option>
                                                <option value="0" selected>False</option>
                                            </select>
                                        </div>
                                        <div class="form-group">
                                            <label>Max Query</label>
                                            <input type="number" step="any" name="maxQuery" class="form-control"
                                                   placeholder="4000">
                                        </div>
                                        <div class="form-group">
                                            <label>Momentum</label>
                                            <input type="number" step="any" name="momentum" class="form-control"
                                                   placeholder="0">
                                        </div>
                                        <div class="form-group">
                                            <label>Alpha</label>
                                            <input type="number" step="any" name="alpha" class="form-control"
                                                   placeholder="0.2">
                                        </div>
                                        <div class="form-group">
                                            <label>Beta</label>
                                            <input type="number" step="any" name="beta" class="form-control"
                                                   placeholder="0.001">
                                        </div>
                                        <div class="form-group">
                                            <label>Iterations</label>
                                            <input type="number" step="any" name="iterations" class="form-control"
                                                   placeholder="1">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                        <button class="btn btn-primary">保存</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>


<!--自适应评估结果-->
<div class="modal fade" id="aotuEvaResultModal" tabindex="-1" role="dialog" aria-labelledby="aotuEvaResulModalLabel"
     aria-hidden="true">
    <div class="modal-dialog" style="max-width: 950px;" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="aotuEvaResulModalLabel">自适应评估结果</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">

            </div>
        </div>
    </div>
</div>


<script type="text/javascript">

    let formParam = {}

    let attackSelected = 'ta'

    let attackType = 'black-box'


    // 切换黑盒白盒算法
    $('.attack-type-tabs>a').click(function () {
        $('.attack-type-tabs>a').removeClass('active')
        $(this).addClass('active')
        $('.attack-type').hide()
        attackType = $(this).data('target')
        $('#' + attackType).show().find('.attack-algorithm-tabs>a').get(0).dispatchEvent(new Event('click'))
    })

    // 切换攻击算法
    $('.attack-algorithm-tabs>a').click(function () {
        $('.attack-algorithm-tabs>a').removeClass('active')
        $(this).addClass('active')
        $('.attack-algorithm-form').hide()
        attackSelected = $(this).data('target')
        $('#' + attackSelected + '-form').show()
    })


    $('.attack-algorithm-form').submit(function (e) {
        e.preventDefault()
        let params = $(this).serializeArray()
        formParam = {}
        params.forEach(item => {
            formParam[item.name] = item.value
        })
        // $(this)[0].reset()
        $('#attackFormModal').modal('hide')
        $('.custom-select-attack').val(attackSelected)
        return false
    })

    function chooseFile(inputFile, textTarget, imageTarget) {
        let files = $(inputFile)[0].files
        if (files.length) {
            let reader = new FileReader()
            reader.onload = function (event) {
                $('#' + textTarget).val(event.target.result);
                $(imageTarget).attr('src', event.target.result).show()
                $(inputFile).val('')
            };
            reader.readAsDataURL(files[0]);
        }
    }

    function onChangeCwTargeted(target, inputClass) {
        if (target.value === '1') {
            $(inputClass).attr('disabled', true)
        } else {
            $(inputClass).attr('disabled', false)
        }
    }

    // $('#ta-targeted').get(0).dispatchEvent(new Event('change'))
    // $('#aotu-eva-ta-targeted').get(0).dispatchEvent(new Event('change'))


    function attack() {
        if (Object.keys(formParam).length === 0) {
            alert('请选择攻击算法')
            return
        }
        let originImg = $('#origin-img').val()
        if (!originImg) {
            alert('请选择图片')
            return
        }
        let params = {}
        $('#attack-form').serializeArray().forEach(item => {
            params[item.name] = item.value
        })
        const loading = layer.load(2, {
            shade: [0.6, '#000']
        })
        let formParamBak = {}
        Object.keys(formParam).forEach(key => {
            if (formParam[key] !== ''){
                formParamBak[key] = formParam[key]
            }
        })
        $.ajax({
            url: '/api/alg',
            // url: './alg.json',
            type: 'POST',
            // type: 'GET',
            contentType: 'application/json;charset=utf-8',
            data: JSON.stringify({
                ...params,
                attach: formParamBak
            }),
            responseType: 'json',
            success: function (data) {
                $('#attackResultModal').modal('show')
                $('#attackResultModal .modal-body .row').html('')
                let names = {
                    'original': 'Model',
                    'adversarial': 'Adversarial',
                    'defense': 'Defense',
                }
                Object.keys(names).forEach(key => {
                    let item = data[key]
                    let carouseItemHtml = ''
                    let indicatorsHtml = ''
                    if (Array.isArray(item.label) && Array.isArray(item.class) && Array.isArray(item.pro)) {
                        item.labelStr = item.label.join('、')
                        item.label.forEach((label, index) => {
                            carouseItemHtml += `
                                    <div class="carousel-item ${index === 0 ? 'active' : ''}">
                                        <p class="card-text mb-0">label: ${label}</p>
                                        <p class="card-text mb-0">class: ${item.class[index]}</p>
                                        <p class="card-text mb-0">pro: ${item.pro[index]}</p>
                                    </div>
                            `
                            indicatorsHtml += `
                                <li data-target="#carouselExampleIndicators_${key}" data-slide-to="${index}" class="${index === 0 ? 'active' : ''}"></li>
                            `
                        })
                    }
                    $('#attackResultModal .modal-body .row').append(`
                         <div class="col-4">
                            <div class="card" style="width: 18rem;">
                                <img src="${key === 'original' ? originImg : 'data:image/png;base64,' + item.img}" class="card-img-top" alt="">
                                <div class="card-body">
                                    <h5 class="card-title">${names[key] || key}</h5>
                                    <div id="carouselExampleIndicators_${key}" class="carousel slide" data-ride="carousel" data-interval="false">
                                      <ol class="carousel-indicators">
                                        ${indicatorsHtml}
                                      </ol>
                                      <div class="carousel-inner">
                                        ${carouseItemHtml}
                                      </div>
                                      <button class="carousel-control-prev" type="button" data-target="#carouselExampleIndicators_${key}" data-slide="prev">
                                        <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                                        <span class="sr-only">Previous</span>
                                      </button>
                                      <button class="carousel-control-next" type="button" data-target="#carouselExampleIndicators_${key}" data-slide="next">
                                        <span class="carousel-control-next-icon" aria-hidden="true"></span>
                                        <span class="sr-only">Next</span>
                                      </button>
                                    </div>
                                    <div class="chart mt-2" id="${key}-chart"></div>
                                </div>
                            </div>
                        </div>
                    `)
                    if (Array.isArray(item.class) && Array.isArray(item.pro)) {
                        setTimeout(() => {
                            let chart = echarts.init(document.getElementById(key + '-chart'))
                            chart.setOption({
                                tooltip: {
                                    trigger: 'axis'
                                },
                                xAxis: {
                                    type: 'category',
                                    data: item.class,
                                    axisLabel: {
                                        //太长了进行省略
                                        formatter: function (value) {
                                            return value.length > 5 ? value.substr(0, 5) + '...' : value;
                                        }
                                    }
                                },
                                yAxis: {
                                    type: 'value'
                                },
                                grid: {
                                    left: '3%',
                                    right: '4%',
                                    bottom: 0,
                                    top: '5%',
                                    containLabel: true
                                },
                                series: [{
                                    name: 'pro',
                                    type: 'bar',
                                    data: item.pro,
                                }]
                            })
                        }, 300)
                    }
                })
            },
            complete: function () {
                layer.close(loading)
            }
        })
    }


    let aotuEvaImages = []
    let chartDatasetMap = {}
    let correctionChart = null

    function chooseDirectory(target) {
        aotuEvaImages = []
        const files = target.files;
        let task = []
        Array.from(files).forEach(file => {
            if (!file.type.match('image.*')) {
                return
            }
            task.push(new Promise(resolve => {
                const reader = new FileReader();
                // 当文件读取完成后
                reader.onload = function (e) {
                    aotuEvaImages.push(e.target.result)
                    resolve()
                };
                reader.readAsDataURL(file); // 将文件读取为 base64
            }))
        });
        Promise.all(task).then(() => {
            $(target).val('')
            $('#aotuEvaFormModal').modal('show')
        })
    }


    // 提交自适应评估
    $('.aotu-eva-form').submit(function (e) {
        e.preventDefault()
        if (aotuEvaImages.length === 0) {
            alert('请选择包含图片的文件夹')
            return false
        }
        let formParam = {
            images: aotuEvaImages
        }
        $('.aotu-eva-form-wrapper').each((index, item) => {
            let itemParam = {}
            $(item).find('input:not(:disabled), select:not(:disabled)').each((idx, formContrl) => {
                let value = $(formContrl).val()
                if (value !== ''){
                    itemParam[$(formContrl).attr('name')] = value
                }
            })
            formParam[$(item).data('form-name')] = itemParam
        })
        const loading = layer.load(2, {
            shade: [0.6, '#000']
        })
        $.ajax({
            url: '/aotu_eva',
            // url: './aotu_eva.json',
            type: 'POST',
            // type: 'GET',
            contentType: 'application/json;charset=utf-8',
            data: JSON.stringify(formParam),
            responseType: 'json',
            success: function (data) {
                let algorithmList = {
                    'origin': 'Model',
                    'attack_by_ta': 'attack by ta',
                    'attack_by_bda': 'attack by bda',
                    'attack_by_nes': 'attack by nes',
                    'attack_by_opt': 'attack by opt',
                }
                let tabsHtml = ''
                let tabContentHtml = ''
                Object.keys(algorithmList).forEach((algorithm, index) => {
                    tabsHtml += `
                        <a class="flex-sm-fill text-sm-center nav-link ${index === 0 ? 'active' : ''}" data-target="${algorithm}-aotu-eva-result" data-name="${algorithm}" href="#">${algorithmList[algorithm] || algorithm}</a>
                    `
                    let tabContentCardHtml = ''
                    let algorithmItem = data[algorithm]
                    console.log(algorithmItem)
                    let modelList = ['alex', 'effiv2', 'faster', 't2t']
                    let dataset = []
                    modelList.forEach(model => {
                        let item = algorithmItem[model]
                        dataset.push({
                            name: model,
                            value: item.correction
                        })
                        let carouseItemHtml = ''
                        let indicatorsHtml = ''
                        if (Array.isArray(item.label) && Array.isArray(item.class) && Array.isArray(item.pro)) {
                            item.labelStr = item.label.join('、')
                            item.label.forEach((label, idx) => {
                                let images = algorithmItem.img || item.img
                                carouseItemHtml += `
                                    <div class="carousel-item ${idx === 0 ? 'active' : ''}">
                                        <img src="${algorithm === 'origin' ? aotuEvaImages[idx] : 'data:image/png;base64,' + images[idx][0]}" class="card-img-top w-100 mb-2" alt="">
                                        <p class="card-text mb-0">label: ${label.join('、')}</p>
                                        <p class="card-text mb-0">class: ${item.class[idx].join('、')}</p>
                                        <p class="card-text mb-2">pro: ${item.pro[idx].join('、')}</p>
                                    </div>
                            `
                                indicatorsHtml += `
                                    <li data-target="#carouselExampleIndicators_${algorithm}_${model}" data-slide-to="${idx}" class="${idx === 0 ? 'active' : ''}"></li>
                             `
                            })
                        }
                        tabContentCardHtml += `
                             <div class="col-6">
                                <div class="card mb-4" >
                                    <div class="card-body">
                                        <h5 class="card-title">${model}</h5>
                                        <div id="carouselExampleIndicators_${algorithm}_${model}" class="carousel slide" data-ride="carousel" data-interval="false">
                                          <ol class="carousel-indicators">
                                            ${indicatorsHtml}
                                          </ol>
                                          <div class="carousel-inner">
                                            ${carouseItemHtml}
                                          </div>
                                          <button class="carousel-control-prev" type="button" data-target="#carouselExampleIndicators_${algorithm}_${model}" data-slide="prev">
                                            <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                                            <span class="sr-only">Previous</span>
                                          </button>
                                          <button class="carousel-control-next" type="button" data-target="#carouselExampleIndicators_${algorithm}_${model}" data-slide="next">
                                            <span class="carousel-control-next-icon" aria-hidden="true"></span>
                                            <span class="sr-only">Next</span>
                                          </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        `
                    })
                    chartDatasetMap[algorithm] = dataset
                    tabContentHtml += `
                         <div id="${algorithm}-aotu-eva-result" class="aotu-eva-result mt-3">
                            <div class="row">
                                ${tabContentCardHtml}
                            </div>
                         </div>
                    `
                })
                $('#aotuEvaResultModal .modal-body').html(`
                     <nav class="nav nav-pills flex-column flex-sm-row aotu-eva-tabs">
                        ${tabsHtml}
                    </nav>
                    ${tabContentHtml}
                    <div class="chart mt-2" id="correction-chart"></div>
                `)
                setTimeout(() => {
                    correctionChart = echarts.init(document.getElementById('correction-chart'))
                    // 切换自适应评估结果
                    $('.aotu-eva-tabs>a').click(function () {
                        $('.aotu-eva-tabs>a').removeClass('active')
                        $(this).addClass('active')
                        $('.aotu-eva-result').hide()
                        $('#' + $(this).data('target')).show()
                        renderCorrectionChart($(this).data('name'))
                    }).get(0).dispatchEvent(new Event('click'))
                }, 300)
                $('#aotuEvaResultModal').modal('show')
                $('#aotuEvaFormModal').modal('hide')
            },
            complete: function () {
                layer.close(loading)
            }
        })
        return false
    })


    function renderCorrectionChart(algorithm) {
        console.log(algorithm)
        correctionChart.setOption({
            tooltip: {
                trigger: 'axis'
            },
            xAxis: {
                type: 'category',
                data: chartDatasetMap[algorithm].map(item => item.name),
            },
            yAxis: {
                type: 'value'
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: 0,
                top: '5%',
                containLabel: true
            },
            series: [{
                name: 'pro',
                type: 'bar',
                data: chartDatasetMap[algorithm].map(item => item.value),
            }]
        }, true)
    }


</script>

</body>
</html>
